<template>
  <div class="agreement-container">
    <n-card title="协议管理">
      <!-- 搜索和操作栏 -->
      <div class="operation-bar">
        <n-space>
          <n-input
            v-model:value="searchKeyword"
            placeholder="请输入协议名称或描述搜索"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <n-icon><search /></n-icon>
            </template>
          </n-input>
          <n-select
            v-model:value="selectedType"
            :options="typeOptions"
            placeholder="选择协议类型"
            style="width: 200px"
          />
          <n-select
            v-model:value="selectedStatus"
            :options="statusOptions"
            placeholder="选择状态"
            style="width: 150px"
          />
          <n-button type="primary" @click="handleSearch">
            搜索
          </n-button>
          <n-button type="primary" @click="handleCreateAgreement">
            新建协议
          </n-button>
        </n-space>
      </div>

      <!-- 协议列表 -->
      <n-data-table
        :columns="columns"
        :data="agreementList"
        :loading="loading"
        :pagination="pagination"
        @update:page="handlePageChange"
      />

      <!-- 新建/编辑协议对话框 -->
      <n-modal
        v-model:show="showModal"
        :title="modalTitle"
        preset="dialog"
        :style="{ width: '800px' }"
      >
        <n-form
          ref="formRef"
          :model="formModel"
          :rules="rules"
          label-placement="left"
          label-width="100"
          require-mark-placement="right-hanging"
        >
          <n-form-item label="协议名称" path="name">
            <n-input v-model:value="formModel.name" placeholder="请输入协议名称" />
          </n-form-item>
          <n-form-item label="协议类型" path="type">
            <n-select
              v-model:value="formModel.type"
              :options="typeOptions"
              placeholder="请选择协议类型"
            />
          </n-form-item>
          <n-form-item label="描述" path="description">
            <n-input
              v-model:value="formModel.description"
              type="textarea"
              placeholder="请输入协议描述"
            />
          </n-form-item>
          <n-form-item label="协议内容" path="agreementnameinfo">
            <n-input
              v-model:value="formModel.agreementnameinfo"
              type="textarea"
              :autosize="{ minRows: 10, maxRows: 20 }"
              placeholder="请输入协议内容（JSON格式）"
            />
          </n-form-item>
          <n-form-item label="状态" path="status">
            <n-select
              v-model:value="formModel.status"
              :options="statusOptions"
              placeholder="请选择状态"
            />
          </n-form-item>
        </n-form>
        <template #action>
          <n-space>
            <n-button @click="showModal = false">取消</n-button>
            <n-button type="primary" @click="handleSubmit">确定</n-button>
          </n-space>
        </template>
      </n-modal>

      <!-- 查看协议详情抽屉 -->
      <n-drawer
        v-model:show="showDrawer"
        :width="600"
        :placement="'right'"
        title="协议详情"
      >
        <n-descriptions bordered>
          <n-descriptions-item label="协议名称">
            {{ currentAgreement.name }}
          </n-descriptions-item>
          <n-descriptions-item label="协议类型">
            {{ currentAgreement.type }}
          </n-descriptions-item>
          <n-descriptions-item label="状态">
            <n-tag :type="currentAgreement.status === 'enabled' ? 'success' : 'warning'">
              {{ currentAgreement.status === 'enabled' ? '启用' : '禁用' }}
            </n-tag>
          </n-descriptions-item>
          <n-descriptions-item label="创建时间">
            {{ currentAgreement.createTime }}
          </n-descriptions-item>
          <n-descriptions-item label="更新时间">
            {{ currentAgreement.updateTime }}
          </n-descriptions-item>
          <n-descriptions-item label="创建者">
            {{ currentAgreement.creator }}
          </n-descriptions-item>
          <n-descriptions-item label="描述">
            {{ currentAgreement.description }}
          </n-descriptions-item>
        </n-descriptions>
        <n-divider>协议内容</n-divider>
        <n-code :code="formatJson(currentAgreement.agreementnameinfo)" language="json" />
      </n-drawer>

      <!-- 删除确认对话框 -->
      <delete-confirm-dialog
        v-model:show="showDeleteModal"
        :content="`确定要删除协议「${agreementToDelete?.name || ''}」吗？此操作不可恢复。`"
        @confirm="handleDeleteConfirm"
      />
    </n-card>
  </div>
</template>

<script setup>
import { ref, onMounted, h } from 'vue'
import { Search } from '@vicons/ionicons5'
import { getAgreementList, createAgreement, getAgreementDetail, updateAgreementStatus, deleteAgreement } from '@/api/agreement'
// import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue'
import { 
  useMessage,
  NButton,
  NSpace,
  NTag,
  NIcon,
  NCard,
  NInput,
  NSelect,
  NDataTable,
  NModal,
  NForm,
  NFormItem,
  NDrawer,
  NDivider,
  NDescriptions,
  NDescriptionsItem,
  NCode
} from 'naive-ui'

const message = useMessage()

// 搜索条件
const searchKeyword = ref('')
const selectedType = ref(null)
const selectedStatus = ref(null)

// 表格数据
const loading = ref(false)
const agreementList = ref([])
const pagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 30, 40]
})

// 表格列定义
const columns = [
  {
    title: '协议名称',
    key: 'name',
    width: 200
  },
  {
    title: '类型',
    key: 'type',
    width: 120
  },
  {
    title: '描述',
    key: 'description',
    ellipsis: true
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    render(row) {
      return h(
        NTag,
        {
          type: row.status === 'enabled' ? 'success' : 'warning'
        },
        { default: () => (row.status === 'enabled' ? '启用' : '禁用') }
      )
    }
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    render(row) {
      return h(
        NSpace,
        {},
        {
          default: () => [
            h(
              NButton,
              {
                size: 'small',
                onClick: () => handleViewDetail(row)
              },
              { default: () => '查看' }
            ),
            h(
              NButton,
              {
                size: 'small',
                type: 'primary',
                onClick: () => handleEdit(row)
              },
              { default: () => '编辑' }
            ),
            h(
              NButton,
              {
                size: 'small',
                type: row.status === 'enabled' ? 'warning' : 'success',
                onClick: () => handleToggleStatus(row)
              },
              { default: () => (row.status === 'enabled' ? '禁用' : '启用') }
            ),
            h(
              NButton,
              {
                size: 'small',
                type: 'error',
                onClick: () => handleDelete(row)
              },
              { default: () => '删除' }
            )
          ]
        }
      )
    }
  }
]

// 选项数据
const typeOptions = [
  { label: '通信协议', value: '通信协议' },
  { label: '安全协议', value: '安全协议' },
  { label: '数据协议', value: '数据协议' }
]

const statusOptions = [
  { label: '启用', value: 'enabled' },
  { label: '禁用', value: 'disabled' }
]

// 表单相关
const showModal = ref(false)
const modalTitle = ref('新建协议')
const formRef = ref(null)
const formModel = ref({
  name: '',
  type: '',
  description: '',
  agreementnameinfo: '',
  status: 'enabled'
})

const rules = {
  name: {
    required: true,
    message: '请输入协议名称',
    trigger: 'blur'
  },
  type: {
    required: true,
    message: '请选择协议类型',
    trigger: 'change'
  },
  agreementnameinfo: {
    required: true,
    message: '请输入协议内容',
    trigger: 'blur',
    validator(rule, value) {
      try {
        if (!value) return false
        JSON.parse(value)
        return true
      } catch (e) {
        return false
      }
    }
  }
}

// 详情抽屉
const showDrawer = ref(false)
const currentAgreement = ref({})

// 删除相关
const showDeleteModal = ref(false)
const agreementToDelete = ref(null)

// 方法定义
const loadData = async () => {
  loading.value = true
  try {
    const res = await getAgreementList({
      page: pagination.value.page,
      pageSize: pagination.value.pageSize,
      keyword: searchKeyword.value,
      type: selectedType.value,
      status: selectedStatus.value
    })
    if (res.code === 200) {
      agreementList.value = res.data.list
      pagination.value.itemCount = res.data.pagination.total
    }
  } catch (error) {
    message.error('加载数据失败')
  }
  loading.value = false
}

const handleSearch = () => {
  pagination.value.page = 1
  loadData()
}

const handlePageChange = (page) => {
  pagination.value.page = page
  loadData()
}

const handleCreateAgreement = () => {
  modalTitle.value = '新建协议'
  formModel.value = {
    name: '',
    type: '',
    description: '',
    agreementnameinfo: '',
    status: 'enabled'
  }
  showModal.value = true
}

const handleEdit = (row) => {
  modalTitle.value = '编辑协议'
  formModel.value = { ...row }
  formModel.value.agreementnameinfo = JSON.stringify(row.agreementnameinfo, null, 2)
  showModal.value = true
}

const handleSubmit = async () => {
  await formRef.value?.validate()
  try {
    const data = {
      ...formModel.value,
      agreementnameinfo: JSON.parse(formModel.value.agreementnameinfo)
    }
    const res = await createAgreement(data)
    if (res.code === 200) {
      message.success('保存成功')
      showModal.value = false
      loadData()
    }
  } catch (error) {
    message.error('保存失败')
  }
}

const handleViewDetail = async (row) => {
  try {
    const res = await getAgreementDetail(row.id)
    if (res.code === 200) {
      currentAgreement.value = res.data
      showDrawer.value = true
    }
  } catch (error) {
    message.error('获取详情失败')
  }
}

const handleToggleStatus = async (row) => {
  try {
    const newStatus = row.status === 'enabled' ? 'disabled' : 'enabled'
    const res = await updateAgreementStatus(row.id, newStatus)
    if (res.code === 200) {
      message.success(newStatus === 'enabled' ? '启用成功' : '禁用成功')
      loadData()
    }
  } catch (error) {
    message.error('操作失败')
  }
}

const handleDelete = (row) => {
  agreementToDelete.value = row
  showDeleteModal.value = true
}

const handleDeleteConfirm = async () => {
  try {
    loading.value = true
    await deleteAgreement(agreementToDelete.value.id)
    message.success('删除成功')
    await loadData() // 重新加载列表
  } catch (error) {
    message.error('删除失败：' + error.message)
  } finally {
    loading.value = false
    showDeleteModal.value = false
    agreementToDelete.value = null
  }
}

const formatJson = (json) => {
  if (typeof json === 'string') {
    try {
      return JSON.stringify(JSON.parse(json), null, 2)
    } catch (e) {
      return json
    }
  }
  return JSON.stringify(json, null, 2)
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.agreement-container {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
}
</style> 